package com.hao.tool.common.util;

import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * http工具类
 *
 * @author sawyer
 * @date 2018-03-20 22:25
 */
public class HttpUtil {

    /**
     * 判断是否为ajax请求
     */
    public static boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }


    /**
     * 获取 HttpServletRequest
     */
    public static HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

    /**
     * 获取  HttpServletRequest
     *
     * @return request
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 获取客户端IP
     * <p>
     * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。<br/>
     * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
     * 如果还不存在则调用etRemoteAddr()
     * </p>
     */
    public static String getIpAddress() {
        HttpServletRequest request = getRequest();
        return getIpByRequest(request);
    }


    public static String getIpByRequest(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        // 多次反向代理后会有多个IP值，第一个为真实IP
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            ip = Splitter.on(",").splitToList(ip).get(0);
        } else {
            ip = request.getRemoteAddr();
        }

        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            return "127.0.0.1";
        }

        return ip;
    }


    /**
     * 用指定分隔符替换ip中的.或：
     *
     * @param replacement 分隔符
     * @return 替换后的ip，如：127-0-0-1
     */
    public static String getIpAddr(String replacement) {
        String temp = CharMatcher.is(':').replaceFrom(Strings.nullToEmpty(getIpAddress()), replacement);
        return CharMatcher.is('.').replaceFrom(temp, replacement);
    }


    public static Boolean isAjax() {
        String requestType = getRequest().getHeader("X-Requested-With");
        return "XMLHttpRequest".equalsIgnoreCase(requestType) ? Boolean.TRUE : Boolean.FALSE;
    }

    public static void printJson(HttpServletResponse response, String content) {
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(content);
            pw.flush();
        } catch (Exception var3) {
            var3.printStackTrace();
        }

    }
}
